﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Activity.API
{
    public static class ExportFeedBackReportHandler
    {
        public static string Export(string mid, DataSet dtSource, string strFileName)
        {
            var strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取或设置包含该应用程序的目录的名称。
            if (!Directory.Exists(strPath + "upfile"))
            {
                Directory.CreateDirectory(strPath + "UploadFile\\Excel"); //不存在就创建文件夹 } 
            }
            if (!Directory.Exists(strPath + "UploadFile\\Excel"))
            {
                Directory.CreateDirectory(strPath + "UploadFile\\Excel"); //不存在就创建文件夹 } 
            }
            var dyInfo = new DirectoryInfo(strPath + "UploadFile\\Excel");
            try
            {
                //获取文件夹下所有的文件
                foreach (FileInfo feInfo in dyInfo.GetFiles())
                {
                    //判断文件日期是否小于2小时，是则删除
                    if (feInfo.CreationTime < DateTime.Now.AddHours(-1))
                        feInfo.Delete();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            var fieldName = strFileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            var filePath = strPath + "UploadFile\\Excel\\" + fieldName;
            MemoryStream ms = ExportDataSetToExcelPageCount(mid, dtSource) as MemoryStream;
            FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            byte[] data = ms.ToArray();
            fs.Write(data, 0, data.Length);
            fs.Flush();
            fs.Close();
            ms.Close();
            data = null;
            ms = null;
            fs = null;

            return filePath.Replace("\\", "#"); 
        }
    }
}
